<template>
  <div class="statistics-container electrical-ledger-page">
    <div class="page-header ledger-filters">
      <el-form :inline="true" :model="queryParams" size="small">
        <el-form-item label="设备编号">
          <el-select
            v-model="queryParams.deviceId"
            placeholder="请选择设备"
            clearable
            filterable
            style="width: 240px"
          >
            <el-option
              v-for="item in deviceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="窗口时间">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            :default-time="['00:00:00', '23:59:59']"
            style="width: 420px"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" icon="el-icon-download" @click="handleExport">导出</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="page-content">
      <div class="card">
        <div class="card-body">
          <el-table
            v-loading="loading"
            :data="tableData"
            stripe
            border
            :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 500 }"
          >
            <el-table-column label="序号" width="60" align="center">
              <template slot-scope="scope">
                {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="deviceName" label="设备名称" min-width="160" show-overflow-tooltip />

            <el-table-column
              prop="windowStart"
              label="窗口开始时间"
              min-width="170"
              :formatter="formatDateColumn"
            />
            <el-table-column
              prop="windowEnd"
              label="窗口结束时间"
              min-width="170"
              :formatter="formatDateColumn"
            />
            <el-table-column prop="granularityMinutes" label="聚合粒度(分钟)" min-width="130" align="center" />
            <el-table-column prop="sampleCount" label="样本数量" min-width="110" align="center" />

            <el-table-column prop="avgIa" label="A相电流平均值" min-width="140" :formatter="formatNumber" />
            <el-table-column prop="avgIb" label="B相电流平均值" min-width="140" :formatter="formatNumber" />
            <el-table-column prop="avgIc" label="C相电流平均值" min-width="140" :formatter="formatNumber" />
            <el-table-column prop="avgUab" label="Uab电压平均值" min-width="140" :formatter="formatNumber" />
            <el-table-column prop="avgUbc" label="Ubc电压平均值" min-width="140" :formatter="formatNumber" />
            <el-table-column prop="avgUca" label="Uca电压平均值" min-width="140" :formatter="formatNumber" />
            <el-table-column prop="avgPowerfactor" label="功率因数平均值" min-width="150" :formatter="formatNumber" />
            <el-table-column prop="energyKwh" label="有功能量(kWh)" min-width="150" :formatter="formatNumber" />
            <el-table-column prop="reactiveEnergy" label="无功能量(kVarh)" min-width="150" :formatter="formatNumber" />
            <el-table-column prop="qualityRate" label="有效数据占比" min-width="140" :formatter="formatNumber" />
          </el-table>

          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            @pagination="handlePagination"
            class="ledger-pagination"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { listDeviceElectricalLedger } from '@/views/statistics/api/deviceElectricalLedgerApi'
import { getHostInfo } from '@/views/statistics/api/screenApi'

export default {
  name: 'DeviceElectricalLedgerPage',
  components: { Pagination },
  data() {
    return {
      loading: false,
      tableData: [],
      total: 0,
      dateRange: [],
      deviceOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceId: ''
      }
    }
  },
  created() {
    this.fetchDeviceOptions()
    this.getList()
  },
  methods: {
    // 获取设备下拉选项
    async fetchDeviceOptions() {
      try {
        const res = await getHostInfo()
        if (res.code === 200 && Array.isArray(res.data)) {
          this.deviceOptions = res.data
            .filter(item => item && item.device_kg_id)
            .map(item => ({
              label: item.device_name || item.device_id,
              value: item.device_kg_id
            }))
        } else {
          this.deviceOptions = []
        }
      } catch (error) {
        console.error('获取设备列表失败', error)
        this.deviceOptions = []
      }
    },
    // 查询台账
    async getList() {
      this.loading = true
      try {
        const params = this.buildQueryParams(true)
        const { rows, total } = await listDeviceElectricalLedger(params)
        this.tableData = rows || []
        this.total = total || 0
      } catch (error) {
        console.error('获取设备电气台账失败', error)
        this.tableData = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    // 组装查询参数
    buildQueryParams(includePage = false) {
      const params = {}
      if (includePage) {
        params.pageNum = this.queryParams.pageNum
        params.pageSize = this.queryParams.pageSize
      }
      if (this.queryParams.deviceId) {
        params.deviceId = this.queryParams.deviceId.trim()
      }
      if (Array.isArray(this.dateRange) && this.dateRange.length === 2) {
        params.windowStart = this.dateRange[0]
        params.windowEnd = this.dateRange[1]
      }
      return params
    },
    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置
    resetQuery() {
      this.dateRange = []
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.queryParams.deviceId = ''
      this.getList()
    },
    // 导出
    handleExport() {
      const params = this.buildQueryParams(false)
      this.download(
        'iot/device-electrical-ledger/export',
        params,
        `device_electrical_ledger_${new Date().getTime()}.xlsx`
      )
    },
    // 分页变化
    handlePagination({ page, limit }) {
      this.queryParams.pageNum = page
      this.queryParams.pageSize = limit
      this.getList()
    },
    // 表格时间格式化
    formatDateColumn(row, column, cellValue) {
      return this.formatDate(cellValue)
    },
    // 通用时间格式化
    formatDate(value) {
      if (!value) {
        return '--'
      }
      return value.replace('T', ' ')
    },
    // 数值格式化
    formatNumber(row, column, cellValue) {
      if (cellValue === null || cellValue === undefined || cellValue === '') {
        return '--'
      }
      return cellValue
    }
  }
}
</script>

<style scoped lang="scss">
@import '@/views/statistics/style/screen.scss';

.electrical-ledger-page {
  .ledger-filters {
    .el-form-item {
      margin-bottom: 12px;
    }
  }

  .card-body {
    padding: 20px;
  }

  .ledger-pagination {
    margin-top: 20px;
    text-align: right;
  }
}
</style>
